package com.aier.controller.forwarder;

import com.aier.bean.common.CommonResult;
import com.aier.bean.common.GlobalCode;
import com.aier.bean.forwarder.ForwarderCode;
import com.aier.bean.forwarder.FreightForwarder;
import com.aier.exception.CastException;
import com.aier.service.forwarder.FreightForwarderService;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * 货代controller
 */
@Controller
@CrossOrigin
@RequestMapping("/freight_forwarder")
public class FreightForwarderController {

    @Autowired
    private FreightForwarderService freightForwarderService;

    @RequestMapping("/save")
    @ResponseBody
    public CommonResult saveFreightForwarder(@RequestBody FreightForwarder freightForwarder){
        freightForwarderService.saveFreightForwarder(freightForwarder);
        return CommonResult.success();
    }

    @RequestMapping("/modify")
    @ResponseBody
    public CommonResult modifyFreightForwarder(@RequestBody FreightForwarder freightForwarder){
        freightForwarderService.modifyFreightForwarder(freightForwarder);
        return CommonResult.success();
    }

    @RequestMapping("/remove_by_id")
    @ResponseBody
    public CommonResult removeFreightForwarder(@RequestBody Map<String,String> map){
        freightForwarderService.removeFreightForwarder(map.get("forwarderId"));
        return CommonResult.success();
    }


    @RequestMapping("/get_one_month")
    @ResponseBody
    public CommonResult getFreightForwarderOneMonth(){
        List<FreightForwarder> freightForwarderList = freightForwarderService.getFreightForwarderOneMonth();
        return CommonResult.success(freightForwarderList);
    }

    @RequestMapping("/get_by_fba")
    @ResponseBody
    public CommonResult getFreightForwarderByFba(@RequestBody Map<String,String> map){
        List<FreightForwarder> freightForwarderList = freightForwarderService.getFreightForwarderByFba(map.get("fbaCode"));
        return CommonResult.success(freightForwarderList);
    }

    @GetMapping("/download_template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 1. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("货代报价信息模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 2. 创建空数据列表
        List<FreightForwarder> emptyList = Collections.emptyList();

        // 3. 使用EasyExcel写入模板
        EasyExcel.write(response.getOutputStream(), FreightForwarder.class)
                .sheet("货代报价信息")
                .doWrite(emptyList);
    }

    @RequestMapping("/batch_upload")
    @ResponseBody
    public CommonResult batchUploadFreightForwarder(@RequestParam("file") MultipartFile file,         // 接收文件
                                               @RequestParam(value = "staffName") String staffName){
        try {
            //记录保存成功的FreightForwarder
            List<FreightForwarder>successList = new ArrayList<>();
            //记录保存失败的FreightForwarder
            List<FreightForwarder>failList = new ArrayList<>();
            List<FreightForwarder> freightForwarderList = EasyExcel.read(file.getInputStream())
                    .head(FreightForwarder.class)
                    .sheet()
                    .doReadSync();
            // 处理数据
            freightForwarderList.forEach(freightForwarder->processFreightForwarder(freightForwarder,successList,failList,staffName));
            Map<String,List<FreightForwarder>> result = new HashMap<>();
            result.put("success",successList);
            result.put("fail",failList);
            return CommonResult.success(result);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.error(GlobalCode.READ_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(GlobalCode.EXPORT_FAIL);
        }
    }


    private void processFreightForwarder(FreightForwarder freightForwarder,List<FreightForwarder>successList,List<FreightForwarder>failList,String staffName) {
        // 2. 枚举值转换（示例）
        freightForwarder.setForwarderCode(convertForwarderCode(freightForwarder.getForwarderCode()));
        freightForwarder.setForwarderId(null);


        // 这里实现业务逻辑，例如：
        // 1. 数据校验
        if (freightForwarder.getWarehouseCode() == null || freightForwarder.getWarehouseCode().isEmpty()) {
            CastException.cast(GlobalCode.WAREHOUSE_CODE_IS_EMPTY);
        }
        if (freightForwarder.getForwarderCode() == null || freightForwarder.getForwarderCode().isEmpty()){
            CastException.cast(GlobalCode.FORWARDER_CODE);
        }
        if (freightForwarder.getTransportChannel() == null || freightForwarder.getTransportChannel().isEmpty()){
            CastException.cast(GlobalCode.TRANSPORT_CHANNEL_IS_EMPTY);
        }
        //不含税价格等于null则赋值为默认值0
        freightForwarder.setSelfFaxedPrice(freightForwarder.getSelfFaxedPrice()==null?BigDecimal.ZERO:freightForwarder.getSelfFaxedPrice());
        //包税价格等于null则赋值为默认值0
        freightForwarder.setTaxInclusivePrice(freightForwarder.getTaxInclusivePrice()==null?BigDecimal.ZERO:freightForwarder.getTaxInclusivePrice());
        if (freightForwarder.getTaxInclusivePrice().compareTo(BigDecimal.ZERO) <= 0 && freightForwarder.getSelfFaxedPrice().compareTo(BigDecimal.ZERO) <= 0){
            CastException.cast(GlobalCode.TAX_AND_EXCLUDE_IS_EMPTY);
        }
        if (freightForwarder.getDestination() == null || freightForwarder.getDestination().isEmpty()){
            CastException.cast(GlobalCode.DESTINATION_IS_EMPTY);
        }
        if (freightForwarder.getSku() == null || freightForwarder.getSku().isEmpty()){
            CastException.cast(GlobalCode.SKU_IS_EMPTY);
        }


        //添加负责业务员信息
        freightForwarder.setStaffName(staffName);

        // 3. 保存到数据库（需要实现Mapper）
        FreightForwarder freightForwarderByParam = freightForwarderService.getFreightForwarderByParam(freightForwarder.getWarehouseCode(),freightForwarder.getForwarderCode(),freightForwarder.getSku(),freightForwarder.getQuoteDate());
        if (freightForwarderByParam == null){
            //不存在，则保存并记录成功FreightForwarder
            freightForwarderService.saveFreightForwarder(freightForwarder);
            successList.add(freightForwarder);
        }else {
            //存在，则记录失败FreightForwarder
            failList.add(freightForwarder);
        }
        System.out.println("处理记录: " + freightForwarder);
    }

    private String convertForwarderCode(String code) {
        // C01-美国，C02-加拿大
        switch (code) {
            case "恒达":
                return ForwarderCode.HENG_DA.getCode();
            case "纽酷":
                return ForwarderCode.NIU_KU.getCode();
            case "志业":
                return ForwarderCode.ZHI_YE.getCode();
            case "迈壹":
                return ForwarderCode.MAI_YI.getCode();
            default:
                return null;
        }
    }

}
